package com.daikun.common.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author earl created 2025-07-16
 * @version init 0.0.1
 */
@Slf4j
public class XiaoYaoJiUtil {

    public static String getXiaoYaoJiToken(String email, String password) {
        String url = "http://1.92.66.23:9999/api/login.json?token=";
        return getXiaoYaoJiToken(url, email, password);
    }

    public static String getXiaoYaoJiToken(String url, String email, String password) {
        Map<String, Object> loginData = MapUtil.builder(new HashMap<String, Object>()).put("email", email).put("password", password).build();
        HttpRequest httpRequest = HttpUtil.createPost(url).form(loginData);
        HttpResponse resp = httpRequest.execute();
        log.info("-> url = {}, email = {}, password = {}, resp = {}", url, email, password, JSONUtil.toJsonStr(resp));
        if (resp == null || resp.getStatus() != 200 || !JSONUtil.isTypeJSON(resp.body()))
            return null;
        JSONObject loginObj = JSONUtil.parseObj(resp.body());
        if (loginObj.getInt("code") != 0)
            return null;
        return loginObj.getJSONObject("data").getStr("token");
    }

}
